package com.wmyg.antifake.controller;

import com.wmyg.antifake.vo.PictureUploadVo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

/**
 * @author 王卓逸
 * @program TODO
 * @description TODO
 * @create 2019-05-26
 */
@RestController
@RequestMapping(value = "/picture")
public class PictureController {

    @PostMapping(value = "/upload")
    public PictureUploadVo uploadPicture(MultipartHttpServletRequest request) {
        PictureUploadVo vo = new PictureUploadVo();
        Iterator<String> itr =  request.getFileNames();
        MultipartFile mpf = null;
        //上传路径
        String filePath =  "/mnt/files/pic/";
        while (itr.hasNext()) {
            mpf = request.getFile(itr.next());
            if (null != mpf) {
                String fileName = mpf.getOriginalFilename();
                String suffixName = fileName.substring(fileName.lastIndexOf("."));
                String newFileName = UUID.randomUUID().toString() + suffixName;
                String fileSavePath = filePath + newFileName;
                try {
                    // 生成图片
                    File file = new File(fileSavePath);
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }

                    mpf.transferTo(file);
                    BufferedImage sourceImg = ImageIO.read(new FileInputStream(file));
                    Integer width = sourceImg.getWidth();
                    Integer height = sourceImg.getHeight();
                    vo.setCode(0);
                    vo.setMessage("Success");
                    vo.setPath(newFileName);
                    vo.setWidth(width);
                    vo.setHeight(height);
                } catch (IOException e) {
                    e.printStackTrace();
                    vo.setCode(1);
                    vo.setMessage(e.getMessage());
                }
            } else {
                vo.setCode(2);
                vo.setMessage("The multipartFile is null");
            }
        }
        return vo;
    }

}
